import Vue from 'vue'
import Vuex from 'vuex'
import jwt_decode from "jwt-decode"
import {asyncRouterMap} from "../router"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: null,
    routers: asyncRouterMap
  },
  mutations: {
    SET_USER(state: any, user: any): void {
      state.user = user;
    },
    SET_ROUTERS(state: any, routers: any): void {
      state.routers = routers;
    },
  },
  getters: {
    user(state: any): any {
      return state.user;
    },
    routers(state: any): any {
      return state.routers;
    },
  },
  actions: {
    async setUser({ state, commit }, user: any) {
      const decoded: any = jwt_decode(user) // 根据token解析出用户信息
      commit('SET_USER', decoded);
      // console.log(decoded)
      const {key} = decoded
      let accessedRouters = filterAsyncRouter(asyncRouterMap, key)
      commit("SET_ROUTERS", accessedRouters)
      // console.log("ac",accessedRouters)
    }

  },
  modules: {
  }

})


function filterAsyncRouter(asyncRouterMap:Array<any>,roles:string) {
  // console.log(asyncRouterMap,roles)
  const accessedRouters = asyncRouterMap.filter(route => {
    if(hasPermission(roles,route)) {
      if(route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

function hasPermission(roles:string,route:any) {
  if(route.meta && route.meta.roles) {
    return route.meta.roles.some((role:string) => role.indexOf(roles) >= 0)
  } else {
    return true
  }
}
